/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.femto.compmod.gui;

import java.awt.*;
import java.io.*;
import javax.swing.*;

public class Console extends JScrollPane {

    PipedInputStream piOut;
    PipedInputStream piErr;
    PipedOutputStream poOut;
    PipedOutputStream poErr;
    JTextArea textArea = new JTextArea();
    OutputStreamRedirector osr;

    private class OutputStreamRedirector extends OutputStream {
        private JTextArea textArea;

        public OutputStreamRedirector(JTextArea ta) {
            textArea = ta;
        }

        @Override
        public void write(int b) throws IOException {
            textArea.append(new String(new byte[] {(byte)b}));
            textArea.setCaretPosition(textArea.getDocument().getLength());
        }

        @Override
        public void flush() throws IOException {
            textArea.repaint();
        }

    }

    public Console() throws IOException {
        osr = new OutputStreamRedirector(textArea);

        System.setOut(new PrintStream(osr));
        System.setErr(new PrintStream(osr));

        textArea.setEditable(false);
        textArea.setFont(new java.awt.Font("Bitstream Vera Sans Mono", 0, 12));
        textArea.setCursor(new Cursor(Cursor.TEXT_CURSOR));

        setViewportView(textArea);
        setVisible(true);

       // new ReaderThread(piOut).start();
       // new ReaderThread(piErr).start();
    }

    class ReaderThread extends Thread {

        PipedInputStream pi;

        ReaderThread(PipedInputStream pi) {
            this.pi = pi;
        }

        public void run() {
            final byte[] buf = new byte[10240];
            try {
                while (true) {
                    final int len = pi.read(buf);
                    if (len == -1) {
                        break;
                    }
                    SwingUtilities.invokeLater(new Runnable() {

                        public void run() {
                            textArea.append(new String(buf, 0, len));

                            // Make sure the last line is always visible

                            textArea.setCaretPosition(textArea.getDocument().getLength());
                            // Keep the text area down to a certain character size
                            int idealSize = 1000;
                            int maxExcess = 5000;
                            int excess = textArea.getDocument().getLength() - idealSize;
                            if (excess >= maxExcess) {
                                textArea.replaceRange("", 0, excess);
                            }
                        }
                    });
                }
            } catch (IOException e) {
            }
        }
    }
}
